﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.BLL;
using System.Data;
using SeDuce.Utility;
using System.IO;
using SeDuce.Model;

public partial class Management_Products_Modify : PageBase
{
    List<Product> products = new List<Product>();

    Lazy_Yu<ProductBLL> lazyProductBLL = new Lazy_Yu<ProductBLL>(() => new ProductBLL());
    public ProductBLL LazyProductBLL
    {
        get { return this.lazyProductBLL.Value; }
    }
    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }
    Lazy_Yu<TypeBLL> lazyTypeBLL = new Lazy_Yu<TypeBLL>(() => new TypeBLL());
    public TypeBLL LazyTypeBLL
    {
        get { return this.lazyTypeBLL.Value; }
    }
    Lazy_Yu<SizeBLL> lazySizeBLL = new Lazy_Yu<SizeBLL>(() => new SizeBLL());
    public SizeBLL LazySizeBLL
    {
        get { return this.lazySizeBLL.Value; }
    }
    Lazy_Yu<ColorBLL> lazyColorBLL = new Lazy_Yu<ColorBLL>(() => new ColorBLL());
    public ColorBLL LazyColorBLL
    {
        get { return this.lazyColorBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtProduct = this.LazyProductBLL.GetProductByProductID(this.GetQueryString("ProductID", false).ToInt());
            if(dtProduct.Rows.Count>0)
            {
                this.lblID.Text = dtProduct.Rows[0]["ProductID"].ToString();
                this.txtName.Text = dtProduct.Rows[0]["ProductName"].ToString();
                this.txtUnitPrice.Text = dtProduct.Rows[0]["UnitPrice"].ToString();
                this.txtSalePrice.Text = dtProduct.Rows[0]["SalePrice"].ToString();
                this.txtUnitPriceUS.Text = dtProduct.Rows[0]["UnitPriceUS"].ToString();
                this.txtSalePriceUS.Text = dtProduct.Rows[0]["SalePriceUS"].ToString();
                this.txtUnitPriceJP.Text = dtProduct.Rows[0]["UnitPriceJP"].ToString();
                this.txtSalePriceJP.Text = dtProduct.Rows[0]["SalePriceJP"].ToString();

                DataTable dtBrands = this.LazyProductBLL.GetBrandsByProductID(dtProduct.Rows[0]["ProductID"].ToString().ToInt());
                this.chklBrands.DataSource = this.LazyBrandBLL.GetBrands();
                this.chklBrands.DataTextField = "BrandName";
                this.chklBrands.DataValueField = "BrandID";
                this.chklBrands.DataBind();
                if (dtBrands.Rows.Count > 0)
                {
                    List<Brand> brands = dtBrands.ToList<Brand>();
                    String[] brandIDs = (from b in brands select b.BrandID.ToString()).ToArray<String>();
                    foreach (ListItem item in this.chklBrands.Items)
                    {
                        if (brandIDs.Contains<string>(item.Value))
                            item.Selected = true;
                    }
                }

                DataTable dtTypes = this.LazyProductBLL.GetTypesByProductID(dtProduct.Rows[0]["ProductID"].ToString().ToInt());
                this.chklTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
                this.chklTypes.DataTextField = "TypeName";
                this.chklTypes.DataValueField = "TypeID";
                this.chklTypes.DataBind();
                if (dtTypes.Rows.Count > 0)
                {
                    List<SeDuce.Model.Type> types = dtTypes.ToList<SeDuce.Model.Type>();
                    String[] typeIDs = (from t in types select t.TypeID.ToString()).ToArray<String>();
                    foreach (ListItem item in this.chklTypes.Items)
                    {
                        if (typeIDs.Contains<string>(item.Value))
                            item.Selected = true;
                    }
                }

                String[] sizes = dtProduct.Rows[0]["Size"].ToString().Split(',');
                this.cnklSizes.DataSource = this.LazySizeBLL.GetSizes().ToList<SeDuce.Model.Size>().OrderBy(t => t.Sort);
                this.cnklSizes.DataTextField = "SizeName";
                this.cnklSizes.DataValueField = "SizeID";
                this.cnklSizes.DataBind();
                foreach (ListItem item in this.cnklSizes.Items)
                {
                    if (sizes.Contains<string>(item.Text))
                        item.Selected = true;
                }

                String[] colors = dtProduct.Rows[0]["Color"].ToString().Split(',');
                this.cnklColors.DataSource = this.LazyColorBLL.GetColor();
                this.cnklColors.DataTextField = "ColorName";
                this.cnklColors.DataValueField = "ColorID";
                this.cnklColors.DataBind();
                foreach (ListItem item in this.cnklColors.Items)
                {
                    if (colors.Contains<string>(item.Text))
                        item.Selected = true;
                }

                this.txtDescription.Text = dtProduct.Rows[0]["Description"].ToString();

                this.rbtnlStatus.DataSource = new Utils().productStatus;
                this.rbtnlStatus.DataTextField = "Name";
                this.rbtnlStatus.DataValueField = "ID";
                this.rbtnlStatus.DataBind();
                foreach (ListItem item in this.rbtnlStatus.Items)
                {
                    if (item.Value == dtProduct.Rows[0]["Status"].ToString())
                        item.Selected = true;
                }
                this.DropDownListFixByValue(this.ddlSeq, dtProduct.Rows[0]["Seq"].ToString());

                this.AddAttributes("OldLogoPath", Server.MapPath(dtProduct.Rows[0]["ImageBig"].ToString()));
                this.AddAttributes("OldLogoFilename", dtProduct.Rows[0]["ImageBig"].ToString());
            }
        }
    }
    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        if (Session["file_info"] != null)
        {
            if (!System.IO.Directory.Exists(Server.MapPath(Misc.filepath)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(Misc.filepath));
            }
            if (!string.IsNullOrEmpty(this.GetAttributes("OldLogoPath")))
            {
                string oldLogo174 = this.GetAttributes("OldLogoPath").Substring(0, this.GetAttributes("OldLogoPath").IndexOf(Path.GetExtension(this.GetAttributes("OldLogoPath")))) + "_174_174" + Path.GetExtension(this.GetAttributes("OldLogoPath"));
                string oldLogo100 = this.GetAttributes("OldLogoPath").Substring(0, this.GetAttributes("OldLogoPath").IndexOf(Path.GetExtension(this.GetAttributes("OldLogoPath")))) + "_100_100" + Path.GetExtension(this.GetAttributes("OldLogoPath"));
                if (File.Exists(this.GetAttributes("OldLogoPath")))
                {
                    File.Delete(this.GetAttributes("OldLogoPath"));
                }
                if (File.Exists(oldLogo174))
                {
                    File.Delete(oldLogo174);
                }
                if (File.Exists(oldLogo100))
                {
                    File.Delete(oldLogo100);
                }
            }
            List<string> file_list_to_delete = new List<string>();
            try
            {
                List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
                ImageHelp imgHelper = new ImageHelp();

                string UploadPath = Server.MapPath(Misc.product_filepath);
                if (!System.IO.Directory.Exists(UploadPath))
                {
                    System.IO.Directory.CreateDirectory(UploadPath);
                }

                foreach (Thumbnail img in thumbnails)
                {
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Replace("-", "");
                    string fullfilename = filename + Path.GetExtension(img.ID).ToLower();
                    string fullfilename_174 = filename + "_174_174" + Path.GetExtension(img.ID).ToLower();
                    string fullfilename_100 = filename + "_100_100" + Path.GetExtension(img.ID).ToLower();
                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename);
                    file_list_to_delete.Add(Misc.product_filepath + "/Temp_" + fullfilename);
                    file_list_to_delete.Add(Misc.product_filepath + "/Temp_Watermark_" + fullfilename);
                    FileStream fs = new FileStream(UploadPath + "\\Temp_" + fullfilename, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(img.Data);
                    bw.Close();
                    fs.Close();

                    //watermark
                    Utils.Watermark(UploadPath + "\\Temp_" + fullfilename, UploadPath + "\\Temp_Watermark_" + fullfilename, Server.MapPath(Misc.watermark2), "CENTER");
                    Utils.Watermark(UploadPath + "\\Temp_Watermark_" + fullfilename, UploadPath + "\\" + fullfilename, Server.MapPath(Misc.watermark1), "BR");

                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename_174);
                    file_list_to_delete.Add(Misc.product_filepath + "/" + fullfilename_100);
                    imgHelper.GetSmaller(UploadPath + "\\" + fullfilename, UploadPath + "/" + filename, 174, 174);
                    imgHelper.GetSmaller(UploadPath + "\\" + fullfilename, UploadPath + "/" + filename, 100, 100);

                    products.Add(new Product()
                    {
                        ProductID = this.lblID.Text.Trim().ToInt(),
                        ProductName = this.txtName.Text.Trim(),
                        UnitPrice = string.IsNullOrEmpty(this.txtUnitPrice.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text.Trim()),
                        SalePrice = this.txtSalePrice.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePrice.Text.Trim()) : 0,
                        Size = String.Join(",", (from item in cnklSizes.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                        Color = String.Join(",", (from item in cnklColors.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                        Description = this.txtDescription.Text.Trim(),
                        Date = DateTime.Now,
                        Status = this.rbtnlStatus.SelectedValue.ToInt(),
                        ImageBig = Misc.product_filepath + "/" + fullfilename,
                        Image174 = Misc.product_filepath + "/" + fullfilename_174,
                        Image100 = Misc.product_filepath + "/" + fullfilename_100,
                        UnitPriceUS = string.IsNullOrEmpty(this.txtUnitPriceUS.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceUS.Text.Trim()),
                        SalePriceUS = this.txtSalePriceUS.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceUS.Text.Trim()) : 0,
                        UnitPriceJP = string.IsNullOrEmpty(this.txtUnitPriceJP.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceJP.Text.Trim()),
                        SalePriceJP = this.txtSalePriceJP.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceJP.Text.Trim()) : 0,
                        Seq = this.ddlSeq.SelectedValue.ToInt()
                    });

                    //替换老图片
                    this.AddAttributes("OldLogoPath", Server.MapPath(Misc.product_filepath + "/" + fullfilename));
                    this.AddAttributes("OldLogoFilename", Misc.product_filepath + "/" + fullfilename);
                }
                if (this.LazyProductBLL.UpdateProduct(products[0], 
                        (from item in chklBrands.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>(),
                        (from item in chklTypes.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>()))
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key3", "javascript:" + string.Format("alert('{0}');window.location.href='List.aspx';", "操作成功!"), true);
                }
                else
                {
                    throw new Exception("保存时发生错误");
                }
            }
            catch (Exception ex)
            {
                foreach (string file in file_list_to_delete)
                {
                    if (File.Exists(Server.MapPath(file)))
                    {
                        File.Delete(Server.MapPath(file));
                    }
                }
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key4", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
            }
            finally
            {
                Session.Remove("file_info");
            }
        }
        else
        {
            bool result = this.LazyProductBLL.UpdateProduct(new Product()
            {
                ProductID = this.lblID.Text.Trim().ToInt(),
                ProductName = this.txtName.Text.Trim(),
                UnitPrice = string.IsNullOrEmpty(this.txtUnitPrice.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPrice.Text.Trim()),
                SalePrice = this.txtSalePrice.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePrice.Text.Trim()) : 0,
                Size = String.Join(",", (from item in cnklSizes.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                Color = String.Join(",", (from item in cnklColors.Items.Cast<ListItem>() where item.Selected select item.Text).ToArray<string>()),
                Description = this.txtDescription.Text.Trim(),
                Date = DateTime.Now,
                Status = this.rbtnlStatus.SelectedValue.ToInt(),
                ImageBig = this.GetAttributes("OldLogoFilename"),
                Image174 = this.GetAttributes("OldLogoFilename").Split('.')[0] + "_174_174." + this.GetAttributes("OldLogoFilename").Split('.')[1],
                Image100 = this.GetAttributes("OldLogoFilename").Split('.')[0] + "_100_100." + this.GetAttributes("OldLogoFilename").Split('.')[1],
                UnitPriceUS = string.IsNullOrEmpty(this.txtUnitPriceUS.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceUS.Text.Trim()),
                SalePriceUS = this.txtSalePriceUS.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceUS.Text.Trim()) : 0,
                UnitPriceJP = string.IsNullOrEmpty(this.txtUnitPriceJP.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtUnitPriceJP.Text.Trim()),
                SalePriceJP = this.txtSalePriceJP.Text.Trim().Length > 0 ? Convert.ToDecimal(this.txtSalePriceJP.Text.Trim()) : 0,
                Seq = this.ddlSeq.SelectedValue.ToInt()
            }, (from item in chklBrands.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>(),
                (from item in chklTypes.Items.Cast<ListItem>() where item.Selected select item.Value.ToInt()).ToList<int>());
            if (result)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key5", "javascript:" + string.Format("alert('{0}');window.location.href='List.aspx';", "操作成功!"), true);
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
            }
        }
    }
    protected void lbtnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("List.aspx");
    }
}